package com.gitee.xmhzzz.component.mqtt.client;


import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONObject;
import com.gitee.xmhzzz.component.mqtt.client.config.MqttConfig;
import com.gitee.xmhzzz.component.mqtt.client.listener.IMqttListener;
import com.gitee.xmhzzz.component.mqtt.client.message.RawMessage;
import com.gitee.xmhzzz.component.mqtt.client.model.MqttReq;
import com.gitee.xmhzzz.component.mqtt.client.model.MqttResp;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import io.netty.handler.codec.mqtt.MqttQoS;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Vertx;
import io.vertx.core.buffer.Buffer;
import io.vertx.mqtt.MqttClient;
import io.vertx.mqtt.MqttClientOptions;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.CountDownLatch;

/**
  * @ClassName
  * @Description
  * @Author wzq
  * @Date 2024/1/11 14:05
  * @Version 1.0
  */
@Slf4j
@Getter
@Setter
public class MqttClientApp extends AbstractVerticle implements IMqttClient {

    public static final Long RECONNECT_INTERVAL = 3000L;

    private static final String allWildcard = "#";
    private static final String singleWildcard = "+";

    private final static String SMART_UP_TOPIC_FORMAT = "$share/%s/%s";

    private final static List<String> topicFormatList = Lists.newArrayList(
            SMART_UP_TOPIC_FORMAT);

    private final MqttConfig mqttConfig;

    private final List<IMqttListener> IMqttListenerList;
    private CountDownLatch countDownLatch;
    private MqttClient mqttClient;
    private String subscribeGroup;

    public MqttClientApp(MqttConfig mqttConfig, List<IMqttListener> IMqttListenerList, String subscribeGroup) {
        this.mqttConfig = mqttConfig;
        this.IMqttListenerList = IMqttListenerList;
        this.subscribeGroup = subscribeGroup;
    }

    @Override
    public boolean isConnect() {
        return Optional.ofNullable(mqttClient).map(MqttClient::isConnected).orElse(false);
    }

    @Override
    public MqttClientApp connect() {
        countDownLatch = new CountDownLatch(1);
        Vertx.vertx().deployVerticle(this);
        return this;
    }

    @Override
    public MqttConfig getMqttConfig() {
        return this.mqttConfig;
    }

    @Override
    public void mqttStop() {
        this.stop();
    }

    @Override
    public void stop() {
        mqttClient.closeHandler(null);
        mqttClient.disconnect((handler) -> {
            if (handler.succeeded()) {
                vertx.close();
                log.info("IMqttClient disConnect success.");
            } else {
                log.error("IMqttClient disConnect fail: ", handler.cause());
            }
        }).exceptionHandler(event -> {
            log.error("IMqttClient fail: ", event.getCause());
        });
    }

    private MqttClientOptions createMqttClientOptions() {
        MqttClientOptions options = new MqttClientOptions();
        options.setClientId("micro-client-" + RandomStringUtils.randomAlphanumeric(17));
        options.setMaxMessageSize(100_000_000);
        options.setKeepAliveInterval(60);
        options.setPassword(mqttConfig.getPassword());
        options.setUsername(mqttConfig.getUsername());
        options.setSsl(mqttConfig.getListenerInfos().isSsl());
        options.setReconnectInterval(RECONNECT_INTERVAL);
        options.setReconnectAttempts(Integer.MAX_VALUE);
        return options;
    }


    private void subscribe() {
        List<String> subscribeTopicSuffix = mqttConfig.getListenerInfos().getSubscribeTopics();
        if (subscribeTopicSuffix == null || subscribeTopicSuffix.isEmpty()) {
            throw new IllegalArgumentException("subscribe topic is empty");
        }
        List<String> subscribeTopic = subscribeTopicSuffix.stream()
                .flatMap(topicSuffix -> topicFormatList.stream().map(t -> String.format(t,subscribeGroup, topicSuffix)))
                .toList();
        subscribeTopic.forEach(topic -> mqttClient.subscribe(topic, 0, s -> {
            if (s.succeeded()) {
                log.info("===>IMqttClient subscribe success.  result[{}] topic[{}]", s.result(), topic);
            } else {
                log.error("===>IMqttClient subscribe fail. topic[{}] ", topic, s.cause());
            }
        }));
    }

    @Override
    public MqttResp publish(MqttReq request) {
        MqttResp response = new MqttResp();
        Buffer payload = StrUtil.isNotBlank(request.getMessageContent()) ? Buffer.buffer(request.getMessageContent()): Buffer.buffer(JSONObject.toJSONString(request));
        mqttClient.publish(request.getTopic(), payload, MqttQoS.valueOf(request.getQos()), false, false, s -> {
            if (s.succeeded()) {
                log.info("===>IMqttClient publish success[{}]", s.result());
            } else {
                log.error("===>IMqttClient publish fail.", s.cause());
            }
        });
        response.setCode(200);
        return response;
    }

    @Override
    public boolean disconnect() {
        if (!isConnect()) {
            log.warn("IMqttClient no connect");
            return false;
        }
        vertx.undeploy(deploymentID(), (handler) -> {
            if (handler.succeeded()) {
                log.info("undeploy success");
            } else {
                log.warn("undeploy fail, {}. ", handler.cause().getMessage(), handler.cause());
            }
        });
        return true;
    }

    public void sync() {
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void start() {
        if (Objects.isNull(this.mqttClient)) {
            this.mqttClient = MqttClient.create(vertx, createMqttClientOptions());
        }
        //接收服务端消息处理handler
        mqttClient.publishHandler(pub -> {
            Buffer buffer = pub.payload();
            String topicName = pub.topicName();
            String[] split = topicName.split("/");
            String string = buffer.toString(StandardCharsets.UTF_8);
            RawMessage rawMessage = new RawMessage();
            HashMap<String, Object> headers = Maps.newHashMap();
            headers.put("topic",topicName);
            headers.put("qos",pub.qosLevel().value());
            rawMessage.setHeaders(headers);
            rawMessage.setMessageContent(string);
            IMqttListenerList.forEach(f -> {
                String topic = f.getTopic();
                if (topicRute(topic, split)){
                    f.onMessage(rawMessage);
                }
            });

        });
        mqttClient.closeHandler(unused -> getVertx().setTimer(RECONNECT_INTERVAL, h -> start()));
        mqttClient.connect(mqttConfig.getListenerInfos().getPort(), mqttConfig.getListenerInfos().getHost(),
                s -> {
                    if (s.succeeded()) {
                        log.info("IMqttClient connect success.");
                        subscribe();
                        countDownLatch.countDown();
                    } else {
                        log.error("IMqttClient connect fail: ", s.cause());
                        if (s.cause() != null) {
                            vertx.setTimer(RECONNECT_INTERVAL, handler -> this.start());
                        }
                    }
                });
    }

    private static boolean topicRute(String topic, String[] split) {
        String[] listenerTopic = topic.split("/");
        boolean flag = true;
        for (int i = 0; i < split.length; i++) {
            if (allWildcard.equals(listenerTopic[i])) {
                break;
            }
            if (singleWildcard.equals(listenerTopic[i])) {
                continue;
            }
            if (!split[i].equals(listenerTopic[i])) {
                flag = false;
                break;
            }
        }
        return flag;
    }

}
